﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Senthil.Mobile.WhereAmI
{
    public static class CustomSoundPlayer
    {
        static IntPtr soundHandle;
        static object lockObject = new object();

        public static event EventHandler<EventArgs> PlayingSound;
        public static event EventHandler<EventArgs> StoppedPlaying;

        // Not threadsafe
        public static void PlaySound(string path)
        {
            lock (lockObject)
            {
                if (soundHandle != IntPtr.Zero)
                    return;

                if (!System.IO.File.Exists(path))
                {
                    throw new InvalidOperationException("Cannot play sound. File " + path + " does not exist.");
                }

                SndOpen(path, ref soundHandle);
                SndPlayAsync(soundHandle, 0x1);
            }

            if (PlayingSound != null)
                PlayingSound(new object(), new EventArgs());
        }

        // Not threadsafe
        public static void StopPlaying()
        {
            lock (lockObject)
            {
                if (soundHandle == IntPtr.Zero)
                    return;

                SndStop((int)SndScope.Process, IntPtr.Zero);

                SndClose(soundHandle);
                soundHandle = IntPtr.Zero;
            }

            if (StoppedPlaying != null)
                StoppedPlaying(new object(), new EventArgs());
        }

        [DllImport("aygshell.dll")]
        internal static extern uint SndOpen(string file, ref IntPtr phSound);

        [DllImport("aygshell.dll")]
        internal static extern uint SndPlayAsync(IntPtr hSound, uint flags);

        [DllImport("aygshell.dll")]
        internal static extern uint SndStop(int soundScope, IntPtr hSound);

        [DllImport("aygshell.dll")]
        internal static extern uint SndClose(IntPtr hSound);



        /// <summary>
        /// SndScope describes a set of sounds.
        /// </summary>
        public enum SndScope
        {
            /// <summary>
            /// SND_SCOPE_PROCESS
            /// </summary>
            Process = 0x1
        }
    }
}
